package com.matrix.tool.ui.tool

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.os.Environment
import android.util.DisplayMetrics
import androidx.activity.enableEdgeToEdge
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.basecore.utils.glide.GlideUtil
import com.matrix.tool.R
import com.matrix.tool.bean.CorpPath
import com.matrix.tool.databinding.ActivityGifcorpBinding
import com.matrix.tool.ui.tool.adapter.CropAdapter
import com.matrix.tool.ui.tool.dialog.RatioPopWin
import com.matrix.tool.utils.cropper.BitmapUtil
import com.matrix.toolutils.common.BitmapUtils
import org.greenrobot.eventbus.EventBus
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * 裁剪
 */
@Route(path = Constant.ARouterPath.GIFCorpActivityPath)
class GIFCorpActivity : BaseActivity<ActivityGifcorpBinding>() {

    private var mAspectRatioX = 1
    private var mAspectRatioY = 1
    private var screen_width: Int = 100
    private var screen_height: Int = 100
    private var path: ArrayList<String> = ArrayList()
    private var corpPath: ArrayList<String> = ArrayList()

    private lateinit var adapter: CropAdapter
    private var position = 0

    override fun getViewBinding(): ActivityGifcorpBinding {
        enableEdgeToEdge()
        return ActivityGifcorpBinding.inflate(layoutInflater)
    }

    override fun initView() {
        val listExtra = intent.getStringArrayListExtra(Constant.ARouterString.PATH)
        if (listExtra != null) {
            path = listExtra
        }
        mViewBinding.recyclerview.layoutManager =
            LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        adapter = CropAdapter(R.layout.crop_item_layout, path, position)
        mViewBinding.recyclerview.adapter = adapter
        LogUtils.i(path)
        mViewBinding.civ.post {
            cropImage(path[0])
        }
    }

    override fun initData() {
        mViewBinding.main.post {
            var rpw = RatioPopWin(this, mViewBinding.main, object : RatioPopWin.RatioClickback {
                override fun onRatio(x: Int, y: Int) {
                    mAspectRatioX = x
                    mAspectRatioY = y
//                    LogUtils.i(path[0])
                    cropImage(path[0])
                }
            })
            rpw.setCropRatio()
        }
    }

    private fun cropImage(mFirstImage: String) {
        var bitmap: Bitmap = BitmapUtil.getBitmapFromSDCard(mFirstImage)
        val dm = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(dm)
        screen_width = dm.widthPixels
        screen_height = dm.heightPixels
        bitmap = resizeSurfaceWithScreen(bitmap, screen_width, screen_height)
        val degree: Int = readPictureDegree(mFirstImage)
        bitmap = rotaingImageView(degree, bitmap)
        mViewBinding.civ.setImageBitmap(bitmap)
        mViewBinding.ivTest.setImageBitmap(mViewBinding.civ.imageBitmap)
        //比例
        mViewBinding.civ.setFixedAspectRatio(mAspectRatioX != 0) //任意大小的裁剪
        if (mAspectRatioX != 0) {
            mViewBinding.civ.setAspectRatio(mAspectRatioX, mAspectRatioY)
        }
    }

    override fun initListener() {
        mViewBinding.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.tvComplete.setOnClickListener {
            if (position < path.size - 1) {
                mViewBinding.tvComplete.text = "下一张"
                var tempPath = saveCorpFile()
                corpPath.add(tempPath)
                position++
                adapter.position = position
                adapter.setList(path)
                cropImage(path[position])
            } else {
                var tempPath = saveCorpFile()
                corpPath.add(tempPath)
                EventBus.getDefault().post(CorpPath(GsonUtils.toJson(corpPath)))
//                LiveEventBus.get<String>(Constant.ARouterString.PATH).post(GsonUtils.toJson(corpPath))
                finish()
            }
            if (position == path.size - 1) {
                mViewBinding.tvComplete.text = "完成"
            }
        }
    }

    fun isFileLocked(filePath: String): Boolean {
        try {
            FileOutputStream(filePath).close() // 尝试打开文件进行写操作（但不实际写入）
            return false // 文件未被占用或可以写入
        } catch (e: IOException) {
            return true // 文件被占用或无法写入
        }
    }

    /**
     * 保存裁剪后的文件
     */
    private fun saveCorpFile(): String {
        val sdCardDir =
            File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path,
                Constant.CachePath
            )
        var savePath = sdCardDir.path
        FileUtils.createOrExistsDir(savePath)
        val croppedImage: Bitmap = mViewBinding.civ.getCroppedImage()
        var name = System.currentTimeMillis().toString() + ".png"
        var pathStr: String = savePath + File.separator + name
        BitmapUtils.saveBitmap(croppedImage, savePath, name)
        return pathStr
    }

    /**
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    private fun rotaingImageView(angle: Int, bitmap: Bitmap): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        val resizedBitmap =
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        return resizedBitmap
    }

    private fun readPictureDegree(path: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return degree
    }

    private fun resizeSurfaceWithScreen(
        bitmap: Bitmap,
        screen_width: Int,
        screen_height: Int
    ): Bitmap {
        var bitmap = bitmap
        var width = bitmap.width
        var height = bitmap.height
        if (width < screen_width && height < screen_height) {
            val scale_width = screen_width * 1.0f / width
            val scale_height = screen_height * 1.0f / height
            val scale = if (scale_width > scale_height) scale_height else scale_width // ???�?�????
            width = (width * scale).toInt()
            height = (height * scale).toInt()
        } else {
            if (width > screen_width) {
                height = height * screen_width / width
                width = screen_width
            }
            if (height > screen_height) {
                width = width * screen_height / height
                height = screen_height
            }
        }
        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false)
        bitmap = BitmapUtil.zoomBitmap(bitmap, width, height)

        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)
        while (baos.toByteArray().size > 1024 * 1024) {
            baos.reset()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
        }
        val isBm = ByteArrayInputStream(baos.toByteArray())
        val bitmap_new = BitmapFactory.decodeStream(isBm, null, null)
        return bitmap_new!!
    }
}